package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DDictionary;
import com.isunland.managesystem.entity.DDictionaryListOriginal;
import com.isunland.managesystem.entity.LocaleWorkQueryCount;
import com.isunland.managesystem.entity.LocaleWorkQueryCountDetailOriginal;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.MultiLinesView;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能: 任务详情界面
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2016/12/12 19:50
 */

public class LocaleWorkQueryCountBaseFragment extends BaseFragment implements View.OnClickListener {
  public static final String EXTRA_ITEM =
      "com.isunland.intelligentFarmbyWJ.ui.TaskDetailFragment.EXTRA_ITEM";
  static final int REQUEST_ALTER = 1;
  static final int TYPE_SAVE = 2;
  static final int TYPE_SUBMIT = 3;
  static final int TYPE_DELETE = 4;
  static final int REQUEST_WORK_START_DATE = 5;
  static final int REQUEST_WORK_END_DATE = 6;
  static final int REQUEST_WORK_TYPE_SHOW_VALUE = 7;
  static final int REQUEST_JOIN_STAFF_NAME = 8;
  static final int REQUEST_WORKER_NAMES = 9;
  static final int REQUEST_DEVICENO_WORK = 10;
  static final int REQUEST_ISPAY_NAME = 11;
  static final int REQUEST_WEATHER_TYPE = 12;
  static final int REQUEST_WORK_AREA = 13;
  static final int REQUEST_CROP_INFO = 14;
  static final int REQUEST_SELECT_FILE = 15;
  static final int REQUEST_UPLOAD = 16;
  @BindView(R.id.sl_worktypeshowvalue) SingleLineView slWorktypeshowvalue;
  //@BindView(R.id.sl_cropname)
  //SingleLineView slCropname;
  @BindView(R.id.sl_workstartdate) SingleLineView slWorkstartdate;
  @BindView(R.id.sl_workenddate) SingleLineView slWorkenddate;
  @BindView(R.id.sl_workernames) SingleLineView slWorkernames;
  @BindView(R.id.sl_areaname) SingleLineView slAreaname;
  @BindView(R.id.sl_region) SingleLineView slRegion;
  //@BindView(R.id.sl_medicineprice)
  //SingleLineView slMedicineprice;
  //@BindView(R.id.sl_dosage)
  //SingleLineView slDosage;
  @BindView(R.id.sl_price) SingleLineView slPrice;
  @BindView(R.id.sl_area_work) SingleLineView slAreaWork;
  @BindView(R.id.sl_otherCost) SingleLineView slOtherCost;
  @BindView(R.id.sl_totalcost) SingleLineView slTotalcost;
  @BindView(R.id.sl_ispayName) SingleLineView slIspayName;
  @BindView(R.id.sl_payedcost) SingleLineView slPayedcost;
  @BindView(R.id.sl_unpay) SingleLineView slUnpay;
  //@BindView(R.id.sl_isConfirmed)
  //SingleLineView slIsConfirmed;
  //@BindView(R.id.sl_confirmedArea)
  //SingleLineView slConfirmedArea;
  //@BindView(R.id.sl_connectedApplyer)
  //SingleLineView slConnectedApplyer;
  @BindView(R.id.sl_regStaffName_work) SingleLineView slRegStaffNameWork;
  @BindView(R.id.sl_regDate_work) SingleLineView slRegDateWork;
  @BindView(R.id.sl_dataStatusName) SingleLineView slDataStatusName;
  @BindView(R.id.sl_joinStaffName) SingleLineView slJoinStaffName;
  @BindView(R.id.sl_deviceIdentNo) SingleLineView slDeviceNo;
  @BindView(R.id.sl_devicename) SingleLineView slDeviceName;
  @BindView(R.id.sl_weatherName) SingleLineView slWeatherName;
  @BindView(R.id.sl_weatherInfo) MultiLinesView slWeatherInfo;
  @BindView(R.id.sl_cropInfoTypeName) SingleLineView slCropInfoTypeName;
  @BindView(R.id.sl_cropInfoNo) SingleLineView slCropInfoNo;
  @BindView(R.id.sl_cropInfoNum) SingleLineView slCropInfoNum;
  @BindView(R.id.sl_technicalParam) SingleLineView slTechnicalParam;
  @BindView(R.id.sl_landDeepth) SingleLineView slLandDeepth;
  @BindView(R.id.sl_warrantyCost) SingleLineView slWarrantyCost;
  @BindView(R.id.sl_oilNum) SingleLineView slOilNum;
  @BindView(R.id.sl_oilNo) SingleLineView slOilNo;
  @BindView(R.id.sl_repairUse) SingleLineView slRepairUse;
  @BindView(R.id.sl_workLocation) SingleLineView slWorkLocation;
  @BindView(R.id.sl_oldWeight) SingleLineView slOldWeight;
  @BindView(R.id.sl_afterProcessWeight) SingleLineView slAfterProcessWeight;
  @BindView(R.id.sl_electricityNum) SingleLineView slElectricityNum;
  @BindView(R.id.sl_waterNum) SingleLineView slWaterNum;
  @BindView(R.id.sl_pickupLocation) SingleLineView slPickupLocation;
  @BindView(R.id.sl_deliveryLocation) SingleLineView slDeliveryLocation;
  @BindView(R.id.sl_soilInfo) SingleLineView slSoilInfo;
  @BindView(R.id.sl_remark_work) SingleLineView slRemarkWork;
  @BindView(R.id.sl_docBlob) SingleLineView slDocBlob;
  @BindView(R.id.sl_checkStaffName) SingleLineView slCheckStaffName;
  //@BindView(R.id.sl_medicinename)
  //SingleLineView slMedicinename;
  LocaleWorkQueryCount mItem;
  //Date mWorkStartDate;
  //Date mWorkEndDate;
  String mId;
  String mWorkerIds;
  String mJoinStaffId;
  String mWorktype;
  String mWeatherId;
  String mIsPay;
  String mDataStatus;
  String mAreaId;

  String mCropInfoTypeCode;
  //String mCropInfoNo;
  String mDocPath;
  FragmentManager mFm;
  /** 农资单位 */
  String mCropInfoMunit;
  String mLat;
  String mLon;
  private View mView;

  //初始化数据
  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mItem = (LocaleWorkQueryCount) getArguments().getSerializable(EXTRA_ITEM);
  }

  //初始化界面
  @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_locale_work_query_count_detail, container, false);
    ButterKnife.bind(this, mView);
    return mView;
  }

  //联网请求.
  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    hideDynamicView();
    initView(mItem);
    volleyPostInit();
    volleyPostInitDynamicView();
  }

  protected void volleyPostInit() {
    if (mItem == null) return;
    if (TextUtils.isEmpty(mItem.getId())) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_OPERATION_TASK_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mItem.getId());
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("获取详情失败!");
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        LocaleWorkQueryCountDetailOriginal original =
            new Gson().fromJson(json, LocaleWorkQueryCountDetailOriginal.class);
        if (original.getResult() == Base.SUCCESS && original.getData() != null) {
          mItem = original.getData();
          initView(mItem);
        } else {
          ToastUtil.show("获取详情失败!");
        }
      }
    });
  }

  void volleyPostUpdateStatus(String id, int type) {
    if (id == null) return;
    String status = null;
    switch (type) {
      case TYPE_SUBMIT:
        status = "submit";
        break;

      case TYPE_DELETE:
        status = "delete";
        break;

      default:
        break;
    }
    if (TextUtils.isEmpty(status)) return;

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_LOCALE_WORK_STATUS);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", id);
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("dataStatus", status);
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base original = new Gson().fromJson(arg0, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show(R.string.success_operation);
          setIfEditSuccess(true);
          mActivity.finish();
        } else {
          ToastUtil.show(R.string.failure_operation);
        }
      }
    });
  }

  private void initView(LocaleWorkQueryCount data) {
    //noinspection deprecation
    slCropInfoTypeName.getViewTitle().setTextColor(getResources().getColor(R.color.blue_click));
    slCropInfoTypeName.setHint("");
    slCropInfoTypeName.setOnClickContentListener(this);
    slJoinStaffName.setHint(getString(R.string.chooseMust));
    if (data == null) {
      mId = UUID.randomUUID().toString();
      mDataStatus = "new";
      return;
    }
    slWorktypeshowvalue.setTextContent(data.getWorktypeshowvalue());
    //slCropname.setTextContent(data.getCropname());
    slWorkernames.setTextContent(data.getWorkernames());
    slWorkstartdate.setTextContent(data.getWorkstartdate());
    slWorkenddate.setTextContent(data.getWorkenddate());
    slPrice.setTextContent(String.valueOf(data.getPrice()));
    slAreaWork.setTextContent(String.valueOf(data.getArea()));
    //slMedicineprice.setTextContent(String.valueOf(data.getMedicineprice()));
    //slDosage.setTextContent(String.valueOf(data.getDosage()));
    slOtherCost.setTextContent(String.valueOf(data.getOthercost()));
    slTotalcost.setTextContent(String.valueOf(data.getTotalcost()));
    slPayedcost.setTextContent(String.valueOf(data.getPayedcost()));
    slUnpay.setTextContent(String.valueOf(data.getUnpay()));
    slRegStaffNameWork.setTextContent(data.getRegStaffName());
    slRegDateWork.setTextContent(data.getRegDate());
    slAreaname.setTextContent(data.getAreaname());
    slRegion.setTextContent(data.getRegion());
    //slIsConfirmed.setTextContent(data.getIsConfirmed());
    //slConfirmedArea.setTextContent(data.getConfirmedArea());
    //slConnectedApplyer.setTextContent(data.getConnectedApplyer());
    slDataStatusName.setTextContent(data.getDataStatusName());
    slIspayName.setTextContent(data.getIspayName());
    slJoinStaffName.setTextContent(data.getJoinStaffName());
    slDeviceNo.setTextContent(data.getDeviceNo());
    slDeviceName.setTextContent(data.getDevicecode());
    slWeatherName.setTextContent(data.getWeatherName());
    slWeatherInfo.setTextContent(data.getWeatherInfo());
    slCropInfoTypeName.setTextContent(data.getCropInfoTypeName());
    slCropInfoNo.setTextContent(data.getCropInfoNo());
    slCropInfoNum.setTextContent(data.getCropInfoNum());
    mCropInfoMunit = data.getCropInfoMunit();
    slCropInfoNum.setTextTitle(getDynamicUnitTilte(data.getCropInfoMunit()));
    slTechnicalParam.setTextContent(data.getTechnicalParam());
    slLandDeepth.setTextContent(data.getLandDeepth());
    slWarrantyCost.setTextContent(data.getWarrantyCost());
    slOilNum.setTextContent(data.getOilNum());
    slOilNo.setTextContent(data.getOilNo());
    slRepairUse.setTextContent(data.getRepairUse());
    slWorkLocation.setTextContent(data.getWorkLocation());
    slOldWeight.setTextContent(data.getOldWeight());
    slAfterProcessWeight.setTextContent(data.getAfterProcessWeight());
    slElectricityNum.setTextContent(data.getElectricityNum());
    slWaterNum.setTextContent(data.getWaterNum());
    slPickupLocation.setTextContent(data.getPickupLocation());
    slDeliveryLocation.setTextContent(data.getDeliveryLocation());
    slSoilInfo.setTextContent(data.getSoilInfo());
    slRemarkWork.setTextContent(data.getRemark());
    slDocBlob.setTextContent(data.getDocBlob());
    slCheckStaffName.setTextContent(data.getCheckStaffName());
    slIspayName.setTextContent(data.getIspayName());

    mId = data.getId();
    mDataStatus = data.getDataStatus();
    //mWorkStartDate = MyDateUtil.parseStringToDate(data.getWorkstartdate());
    //mWorkEndDate = MyDateUtil.parseStringToDate(data.getWorkenddate());
    mWorkerIds = data.getWorkerids();
    mJoinStaffId = data.getJoinStaffId();
    mWorktype = data.getWorktype();
    mWeatherId = data.getWeatherId();
    mIsPay = data.getIspay();
    mAreaId = data.getAreaid();

    mCropInfoTypeCode = data.getCropInfoTypeCode();
    mDocPath = data.getDocPath();
    mLat = data.getLatItude();
    mLon = data.getLongItude();
  }

  /**
   * 禁用所有动态字段
   */
  void hideDynamicView() {
    mAreaId = "";
    mCropInfoTypeCode = "";

    slAreaname.hide();
    slRegion.hide();
    slAreaWork.hide();
    slCropInfoTypeName.hide();
    slCropInfoNo.hide();
    slCropInfoNum.hide();
    slTechnicalParam.hide();
    slLandDeepth.hide();
    slWarrantyCost.hide();
    slOilNum.hide();
    slOilNo.hide();
    slRepairUse.hide();
    slWorkLocation.hide();
    slOldWeight.hide();
    slAfterProcessWeight.hide();
    slElectricityNum.hide();
    slWaterNum.hide();
    slPickupLocation.hide();
    slDeliveryLocation.hide();
    slSoilInfo.hide();
  }

  void showDynamicView(String dynamicStr) {
    ArrayList<String> list = MyStringUtil.splitStr(dynamicStr, MyStringUtil.COMMA);
    if (list == null || list.size() == 0) return;
    hideDynamicView();
    for (String tag : list) {
      if (mView == null) return;
      View dynamicView = mView.findViewWithTag(tag);
      if (dynamicView != null) {
        dynamicView.setVisibility(View.VISIBLE);
      }
    }
  }

  /**
   * 查询作业类型接口,根据当前作业类型,动态显示字段,用于初始化操作
   */
  public void volleyPostInitDynamicView() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_LIST_WORK_TYPE);
    HashMap<String, String> params = new HashMap<>();
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        DDictionaryListOriginal original = new Gson().fromJson(arg0, DDictionaryListOriginal.class);
        ArrayList<DDictionary> rows = original.getRows();
        for (DDictionary item : rows) {
          //默认赋值作业类型
          if (TextUtils.isEmpty(mWorktype)) {
            mWorktype = rows.get(0).getRecordCode();
            slWorktypeshowvalue.setTextContent(rows.get(0).getRecordText());
          }
          if (item.getRecordCode().equals(mWorktype)) {
            showDynamicView(item.getTextField2());
          }
        }
      }
    });
  }

  /**
   * 设置动态的农资单位标题
   */
  String getDynamicUnitTilte(String unit) {
    if (TextUtils.isEmpty(unit)) return slCropInfoNum.getTextTitle();
    String amount = getString(R.string.cropInfoNum);
    String slash = getString(R.string.slash);
    return MyStringUtil.connect(amount, slash, unit);
  }

  @Override public void onClick(View v) {
    if (!(v.getTag() instanceof Integer)) return;
    int id = (int) v.getTag();
    switch (id) {
      case R.id.sl_cropInfoTypeName:
        selectCrop();
        break;
    }
  }

  protected void selectCrop() {
    BaseParams params = new BaseParams();
    params.setId(mId);
    params.setDataStatus(mDataStatus);
    LocaleWorkCropInfoSubListActivity.newInstance(this, LocaleWorkCropInfoSubListActivity.class,
        params, 0);
    //Intent i = new Intent(getActivity(), BaseSearchActivity.class);
    //BaseSearchActivity.setFragment(new CropInfoSearchListFragment());
    //startActivityForResult(i, REQUEST_CROP_INFO);
  }

  protected void setIfEditSuccess(boolean isEditSuccess) {
    Intent intent = new Intent();
    intent.putExtra(LocaleWorkQueryCountListFragment.EXTRA_IF_EDIT, isEditSuccess);
    mActivity.setResult(Activity.RESULT_OK, intent);
  }
}
